package rbk.rours.service.user;

import org.modelmapper.ModelMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Service;

import rbk.rours.common.dto.UserInfoDto;
import rbk.rours.common.entities.UserInfo;
import rbk.rours.common.utils.*;;

@Service
class UserService implements IUserService {
    @Autowired
    NamedParameterJdbcTemplate jdbcTemplate;

    @Autowired
    ModelMapper modelMapper;

    @Autowired
    private UserRepository userRepository;

    @Override
    public JsonResult Login(UserInfoDto request) throws Exception {
        UserInfo u = userRepository.findByName(request.getName());
        if (u == null)
            return JsonResult.errorMsg("未找到该用户");
        if (u.getPassword().equals(request.getPassword()))
            return JsonResult.ok(u.getName());
        else
            return JsonResult.errorMsg("密码错误");
    }

    @Override
    public JsonResult Register(UserInfoDto request) throws Exception {
        UserInfo user = modelMapper.map(request, UserInfo.class);
        UserInfo u = userRepository.findByName(request.getName());
        if (u == null) {
            userRepository.save(user);
            return JsonResult.ok(user.getName());
        } else
            return JsonResult.errorMsg("已存在相同用户名");
    }
}
